package com.scvtc.service.system.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.scvtc.domain.ResResult;
import com.scvtc.domain.dto.common.SystemLoginUser;
import com.scvtc.domain.dto.common.SystemUserLoginDto;
import com.scvtc.domain.dto.system.role.SystemRoleDto;
import com.scvtc.domain.entity.system.SystemRole;
import com.scvtc.domain.entity.system.SystemRoleMenu;
import com.scvtc.domain.vo.PageVo;
import com.scvtc.domain.vo.system.user.UserRoleVo;
import com.scvtc.mapper.system.SystemMenuMapper;
import com.scvtc.mapper.system.SystemRoleMapper;
import com.scvtc.service.system.SystemRoleMenuService;
import com.scvtc.service.system.SystemRoleService;
import com.scvtc.service.system.SystemUserService;
import com.scvtc.utils.BeanCopyUtils;
import com.scvtc.utils.RedisUtil;
import com.scvtc.utils.SecurityUtil;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.scvtc.constants.RedisConstant.USER_LOGIN;
import static com.scvtc.constants.SystemConstants.STATUS_ENABLE;
import static com.scvtc.domain.enums.AppHttpCodeEnum.MISSING_ROLE_MENU;

/**
 * 角色管理(SystemRole)表服务实现类
 *
 * @author yiFei
 * @since 2022-04-13 17:38:28
 */
@Service("systemRoleService")
public class SystemRoleServiceImpl extends ServiceImpl<SystemRoleMapper, SystemRole> implements SystemRoleService {

    @Resource
    private SystemMenuMapper systemMenuMapper;

    @Autowired
    private SystemRoleMenuService systemRoleMenuService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private SystemUserService systemUserService;

    /**
     * 根据 用户id获取 角色信息
     *
     * @param id
     * @return
     */
    @Override
    public ResResult<List<SystemRole>> getRolesByUserId(Long id) {
        // 获取用户 Id
        Long userId = SecurityUtil.getUserId();
        // 数据库查询角色集合
        List<SystemRole> rolesByUserId = getBaseMapper().getRolesByUserId(userId);
        return ResResult.noMsgSuccess(rolesByUserId);
    }

    /**
     * 获取全部菜单
     *
     * @param current
     * @param size
     * @param name
     * @return
     */
    @Override
    public ResResult<PageVo<List<SystemRoleDto>>> listRole(Long current, Long size, String name) {
        // 查询数据
        Page<SystemRole> page = page(new Page<SystemRole>(current, size),
                new LambdaQueryWrapper<SystemRole>()
                        .like(StringUtils.hasText(name), SystemRole::getName, name)
        );
        // 封装信息
        List<SystemRole> records = page.getRecords();
        List<SystemRoleDto> systemRoleDto = BeanCopyUtils.copyBean(records, SystemRoleDto.class);
        long total = page.getTotal();

        return ResResult.noMsgSuccess(new PageVo<>(systemRoleDto, total));
    }

    /**
     * 添加角色
     *
     * @param systemRoleDto
     * @return
     */
    @Override
    public ResResult<?> addRole(SystemRoleDto systemRoleDto) {
        SystemRole systemRole = BeanCopyUtils.copyBean(systemRoleDto, SystemRole.class).setId(null);
        // 条件判断
        if (save(systemRole)) {
            return ResResult.success(systemRole.getId());
        }
        return ResResult.fail();
    }

    /**
     * 用角色id获取菜单
     *
     * @param roleId
     * @return
     */
    @Override
    public ResResult<List<Long>> getMenuByRoleId(Long roleId) {
        // 封装当前 id
        Set<Long> ids = new HashSet<>();
        ids.add(roleId);
        // 根据角色获取菜单
        List<Long> menusByRoleIds = systemMenuMapper.getMenusByRoleIds(ids);
        return ResResult.noMsgSuccess(menusByRoleIds);
    }

    /**
     * 根据用户传入菜单更新角色菜单
     *
     * @param roleId
     * @param menuIds
     * @return
     */
    @Transactional
    @SneakyThrows
    @Override
    public ResResult<?> updateRoleByMenuIds(Long roleId, List<Long> menuIds) {
        // 判断菜单是否减少
        if (CollectionUtils.isEmpty(menuIds)) {
            return ResResult.customize(MISSING_ROLE_MENU);
        }
        // 删除之前的权限
        systemRoleMenuService.remove(
                new LambdaQueryWrapper<SystemRoleMenu>()
                        .eq(SystemRoleMenu::getRoleId, roleId)
        );
        // 添加现在的权限
        List<SystemRoleMenu> roleMenus = menuIds.stream()
                .distinct()
                .map(item -> new SystemRoleMenu(roleId, item))
                .collect(Collectors.toList());
        // 返回信息是为了让前端知道操作成功
        if (systemRoleMenuService.saveBatch(roleMenus)) {
            // 刷新 redis
            refreshAllLoginUser();
            return ResResult.success(roleId);
        }
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        return ResResult.fail();
    }

    /**
     * 删除角色
     *
     * @param id
     * @return
     */
    @Override
    public ResResult<?> deleteRoleById(Long id) {
        // 如果角色和菜单都删除了 ， 就返回成功 否则回滚
        systemRoleMenuService.remove(
                new LambdaQueryWrapper<SystemRoleMenu>()
                        .eq(SystemRoleMenu::getRoleId, id)
        );
        if (remove(new LambdaQueryWrapper<SystemRole>()
                .eq(SystemRole::getId, id))
        ) {
            // 刷新 redis
            refreshAllLoginUser();
            return ResResult.success();
        }
        return ResResult.fail();
    }

    /**
     * 修改角色信息
     *
     * @param systemRoleDto
     * @return
     */
    @Override
    public ResResult<?> updateRole(SystemRoleDto systemRoleDto) {
        SystemRole systemRole = BeanCopyUtils.copyBean(systemRoleDto, SystemRole.class);
        if (updateById(systemRole)) {
            return ResResult.success();
        }
        return ResResult.fail();
    }

    /**
     * 获取全部角色
     *
     * @return
     */
    @Override
    public ResResult<List<UserRoleVo>> getAllRole() {
        List<SystemRole> list = list(new LambdaQueryWrapper<SystemRole>().eq(SystemRole::getStatus, STATUS_ENABLE));
        List<UserRoleVo> userRoleVos = BeanCopyUtils.copyBean(list, UserRoleVo.class);
        return ResResult.noMsgSuccess(userRoleVos);
    }

    /**
     * 异步刷新用户任务
     */
    @Async("taskExecutor")
    public void refreshAllLoginUser() {
        Collection<String> keys = redisUtil.keys(USER_LOGIN.concat("*"));
        for (String key : keys) {
            SystemLoginUser systemLoginUser = redisUtil.getCacheObject(key);
            String username = systemLoginUser.getUsername();
            // TODO 使用加密算法解密 JasyptEncryptorUtil
            String password = systemLoginUser.getPassword();
            // 自动让用户重新登录
            systemUserService.login(new SystemUserLoginDto(username, password));
        }
    }
}

